package cn.kongwg.servlet;

import cn.kongwg.bean.Book;
import cn.kongwg.bean.Cart;
import cn.kongwg.bean.CartItem;
import cn.kongwg.service.BookService;
import cn.kongwg.service.impl.BookServiceImpl;
import cn.kongwg.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author kongwg
 * @create 2021-01-30 18:57
 */
@WebServlet("/cartServlet")
public class CartServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();

    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        int bookId = WebUtils.parseToInt(id, 0);
        Book book = bookService.queryByid(bookId);

        CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice(), book.getPrice());

        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart == null) {
            cart = new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.addItem(cartItem);
        req.getSession().setAttribute("lastName",book.getName());
        System.out.println(cart);

        resp.sendRedirect(req.getHeader("Referer"));

    }

    protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseToInt(req.getParameter("id"), 0);
        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart != null) {

            cart.deleteItem(id);
        }
        resp.sendRedirect(req.getHeader("Referer"));

    }

    protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseToInt(req.getParameter("id"), 0);

        int count = WebUtils.parseToInt(req.getParameter("count"), 1);
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null) {

            cart.updateCount(id, count);
        }
        resp.sendRedirect(req.getHeader("Referer"));


    }

    protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null) {
            cart.clear();

        }
        resp.sendRedirect(req.getHeader("Referer"));

    }


}
